import * as React from 'react';
import { Form } from 'antd';
import FormComponent from '../components/FormComponent'
import { IBookListProps } from '../stores'
import BookModel from '../models/BookModel'


const CollectionCreateForm = Form.create()(FormComponent);
interface IFormValue {
  bookName: string,
  url?: string
}
interface IProps {
  visible: boolean,
  book?: BookModel,
  onCancel(): void,
}

export interface IAddProps extends IProps {
  wrappedComponentRef(): void,
  onCreate(): void,
}

export default class Modal extends React.Component<IBookListProps & IProps> {
  private formRef: FormComponent

  constructor(props: IBookListProps & IProps) {
    super(props)
  }
  public handleCreate = () => {
    const form = this.formRef.props.form;
    form.validateFields((err, values: IFormValue) => {
      if (err) {
        return;
      }
      if (this.props.book) {
        this.props.bookStore.changeBook(this.props.book.id, values.bookName, values.url)
      } else {
        this.props.bookStore.addBook(values.bookName, values.url)
      }

      console.log('Received values of form: ', values);
      form.resetFields();
      this.props.onCancel()
    });
  }

  public saveFormRef = (formRef: FormComponent) => {
    this.formRef = formRef;
  }

  public render() {
    return (
      <CollectionCreateForm
        wrappedComponentRef={this.saveFormRef}
        visible={this.props.visible}
        onCancel={this.props.onCancel}
        book={this.props.book}
        onCreate={this.handleCreate} />
    );
  }
}
